<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '站点列表']" />
    <a-card class="general-card" :title="$t('站点管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="stationName" :label="$t('站点名称')">
                  <a-input
                    v-model="searchForm.stationName"
                    :placeholder="$t('请输入站点名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="province" :label="$t('所在省份')">
                  <a-select
                    v-model="searchForm.province"
                    :placeholder="$t('请选择省份')"
                    allow-clear
                    @change="handleProvinceChange"
                  >
                    <a-option
                      v-for="item in provinceOptions"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="city" :label="$t('所在城市')">
                  <a-select
                    v-model="searchForm.city"
                    :placeholder="$t('请选择城市')"
                    allow-clear
                    :disabled="!searchForm.province"
                  >
                    <a-option
                      v-for="item in cityOptions"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="1">{{ $t('启用') }}</a-option>
                    <a-option :value="0">{{ $t('停用') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  field="partnerId"
                  :label="$t('关联客户')"
                  v-if="userInfo.role === 'admin'"
                >
                  <a-select
                    v-model="searchForm.partnerId"
                    :placeholder="$t('请选择客户')"
                    allow-clear
                    :loading="partnerLoading"
                  >
                    <a-option
                      v-for="partner in partnerOptions"
                      :key="partner.id"
                      :value="partner.id"
                    >
                      {{ partner.partnerName }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('新增') }}
          </a-button>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="站点名称" data-index="stationName" />
          <a-table-column title="所在省份" data-index="province" />
          <a-table-column title="所在城市" data-index="city" />
          <a-table-column title="所在区县" data-index="district" />
          <a-table-column title="详细地址" data-index="address" />
          <a-table-column
            title="关联客户"
            data-index="partnerName"
            v-if="userInfo.role === 'admin'"
          >
            <template #cell="{ record }">
              <span v-if="record.partnerId">{{
                findPartnerName(record.partnerId)
              }}</span>
              <span v-else class="text-muted">未关联</span>
            </template>
          </a-table-column>
          <a-table-column title="站点类型" data-index="stationType">
            <template #cell="{ record }">
              <a-tag :color="getStationTypeColor(record.stationType)">
                {{ getStationTypeText(record.stationType) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '停用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{
                record.createTime
                  ? record.createTime.replace('T', ' ').substring(0, 19)
                  : ''
              }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="180">
            <template #cell="{ record }">
              <div class="operations-wrapper">
                <div class="action-group">
                  <a-tooltip content="编辑站点">
                    <a-button
                      type="primary"
                      size="small"
                      shape="round"
                      @click="openEditDialog(record)"
                    >
                      <template #icon><icon-edit /></template>
                      编辑
                    </a-button>
                  </a-tooltip>
                  <a-tooltip content="查看订单">
                    <a-button
                      type="primary"
                      status="success"
                      size="small"
                      shape="round"
                      @click="viewStationOrders(record)"
                    >
                      <template #icon><icon-file /></template>
                      订单
                    </a-button>
                  </a-tooltip>
                  <a-tooltip content="查看设备">
                    <a-button
                      type="primary"
                      status="warning"
                      size="small"
                      shape="round"
                      @click="viewDevices(record)"
                    >
                      <template #icon><icon-apps /></template>
                      枪桩
                    </a-button>
                  </a-tooltip>
                </div>
              </div>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑对话框 -->
    <a-modal
      v-model:visible="visible"
      :title="isEdit ? '编辑汽车站点' : '新增汽车站点'"
      @before-ok="handleSubmit"
      @close="
        () => {
          console.log('对话框关闭');
        }
      "
      @cancel="
        () => {
          console.log('对话框取消');
        }
      "
      width="800px"
      :footer="false"
      class="station-modal"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        class="station-form"
      >
        <a-card title="基本信息" class="form-card">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="stationName" label="站点名称" required>
                <a-input
                  v-model="form.stationName"
                  placeholder="请输入站点名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="stationType" label="站点类型" required>
                <a-select
                  v-model="form.stationType"
                  placeholder="请选择站点类型"
                >
                  <a-option :value="1">普通站点</a-option>
                  <a-option :value="2">超充站</a-option>
                  <a-option :value="3">液冷超充站</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="status" label="状态">
                <a-radio-group v-model="form.status" type="button">
                  <a-radio :value="1">启用</a-radio>
                  <a-radio :value="0">停用</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                field="partnerId"
                label="关联客户"
                v-if="userInfo.role === 'admin'"
              >
                <a-select
                  v-model="form.partnerId"
                  placeholder="请选择关联客户"
                  allow-search
                  :loading="partnerLoading"
                  @search="searchPartners"
                >
                  <a-option
                    v-for="partner in partnerOptions"
                    :key="partner.id"
                    :value="partner.id"
                  >
                    {{ partner.partnerName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card title="地理位置" class="form-card location-card">
          <a-form-item field="province" label="所在省份" required>
            <a-select
              v-model="form.province"
              placeholder="请选择省份"
              @change="handleFormProvinceChange"
            >
              <a-option
                v-for="item in provinceOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="city" label="所在城市" required>
            <a-select
              v-model="form.city"
              placeholder="请选择城市"
              :disabled="!form.province"
              @change="handleFormCityChange"
            >
              <a-option
                v-for="item in formCityOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="district" label="所在区县">
            <a-select
              v-model="form.district"
              placeholder="请选择区县"
              :disabled="!form.city"
              allow-clear
            >
              <a-option
                v-for="item in districtOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item label="详细地址" required class="address-item">
            <a-input
              v-model="form.address"
              placeholder="请输入详细地址"
              @input="(value: string) => debounceSearchAddress(value)"
            />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" @click="searchAddress">
                <template #icon>
                  <icon-search />
                </template>
                定位
              </a-button>
              <a-button
                @click="
                  () => {
                    if (!form.address) {
                      Message.warning('请先输入详细地址');
                      return;
                    }

                    // 构建完整地址
                    let fullAddress = '';
                    if (form.province) {
                      fullAddress += form.province;
                    }
                    if (form.city) {
                      fullAddress += form.city;
                    }
                    if (form.district) {
                      fullAddress += form.district;
                    }
                    fullAddress += form.address;

                    tryAlternativeSearch(fullAddress);
                  }
                "
              >
                <template #icon>
                  <icon-refresh />
                </template>
                备选定位
              </a-button>
              <a-button @click="openCoordinatePicker">
                <template #icon>
                  <icon-edit />
                </template>
                手动选点
              </a-button>
              <a-button @click="inputCoordinates">
                <template #icon>
                  <icon-code />
                </template>
                输入坐标
              </a-button>
              <a-tooltip>
                <template #content>
                  <div style="max-width: 300px">
                    <p><b>定位</b>：使用高德地图API根据地址查询经纬度</p>
                    <p
                      ><b>备选定位</b
                      >：当主定位方式失败时使用，通过JSONP方式请求</p
                    >
                    <p
                      ><b>手动选点</b
                      >：打开高德地图坐标拾取器，手动选择位置并复制经纬度</p
                    >
                    <p
                      ><b>输入坐标</b>：直接输入经纬度坐标（格式：经度,纬度）</p
                    >
                  </div>
                </template>
                <icon-question-circle />
              </a-tooltip>
            </a-space>
          </a-form-item>

          <a-form-item field="location" label="地理位置">
            <div class="map-container">
              <div id="map-container" style="height: 300px"></div>
              <div class="map-info">
                <p>经度：{{ form.longitude }}</p>
                <p>纬度：{{ form.latitude }}</p>
                <p class="map-tip">提示：点击地图选择位置</p>
              </div>
            </div>
            <!-- 地图加载失败时的备用输入框 -->
            <div v-if="!AMap" class="manual-location-input">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="longitude" label="经度">
                    <a-input-number
                      v-model="form.longitude"
                      placeholder="请输入经度"
                      :precision="6"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="latitude" label="纬度">
                    <a-input-number
                      v-model="form.latitude"
                      placeholder="请输入纬度"
                      :precision="6"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-alert type="warning">
                <template #message>
                  高德地图加载失败，请手动输入经纬度。您可以通过以下方式获取经纬度：
                  <ol>
                    <li
                      >访问
                      <a
                        href="https://lbs.amap.com/tools/picker"
                        target="_blank"
                        >高德坐标拾取器</a
                      ></li
                    >
                    <li>在地图上选择位置，复制经纬度</li>
                    <li>将经度和纬度分别填入上方输入框</li>
                  </ol>
                </template>
              </a-alert>
            </div>
          </a-form-item>
        </a-card>

        <a-card title="联系信息" class="form-card">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="contactPerson" label="联系人">
                <a-input
                  v-model="form.contactPerson"
                  placeholder="请输入联系人"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="contactPhone" label="联系电话">
                <a-input
                  v-model="form.contactPhone"
                  placeholder="请输入联系电话"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="businessHours" label="营业时间">
                <a-input
                  v-model="form.businessHours"
                  placeholder="请输入营业时间，如：08:00-20:00"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item
            field="facilities"
            label="站点设施"
            class="full-width-item"
          >
            <a-textarea
              v-model="form.facilities"
              placeholder="请输入站点设施，如：停车场、候车室、卫生间等"
            />
          </a-form-item>
          <a-form-item field="remark" label="备注" class="full-width-item">
            <a-textarea v-model="form.remark" placeholder="请输入备注" />
          </a-form-item>
        </a-card>

        <div class="form-footer">
          <a-space>
            <a-button @click="visible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 查看位置对话框 -->
    <a-modal
      v-model:visible="mapVisible"
      title="查看站点位置"
      @cancel="mapVisible = false"
      :footer="false"
      width="800px"
    >
      <div id="view-map-container" style="height: 500px"></div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    getCarStationPage,
    addCarStation,
    updateCarStation,
    deleteCarStation,
    CarStationItem as BaseCarStationItem,
    ApiResponse,
    CarStationPageData,
  } from '@/api/station';
  import { getProvinces, getCities, getDistricts, Region } from '@/api/region';
  import {
    getPartnerList,
    PartnerQueryParams,
    getAllPartners,
  } from '@/api/partner';
  import useLoading from '@/hooks/loading';
  import { cloneDeep } from 'lodash';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store';

  // 获取用户信息
  const userInfo = useUserStore();

  // 扩展 CarStationItem 接口以包含 partnerId 字段
  interface CarStationItem extends BaseCarStationItem {
    partnerId?: number;
  }

  // 防抖函数
  function debounce<T extends (...args: any[]) => any>(
    fn: T,
    delay: number
  ): (...args: Parameters<T>) => void {
    let timer: number | null = null;
    return function (this: any, ...args: Parameters<T>): void {
      if (timer) {
        clearTimeout(timer);
      }
      timer = window.setTimeout(() => {
        fn.apply(this, args);
        timer = null;
      }, delay);
    };
  }

  // 获取路由实例
  const router = useRouter();

  // 声明 AMap 类型
  declare global {
    interface Window {
      AMap: any;
      _AMapSecurityConfig: {
        securityJsCode: string;
        serviceHost: string;
      };
    }
  }

  // 高德地图 API 配置
  const AMAP_CONFIG = {
    // 不使用代理服务器
    useProxy: false,
    // 在此处填写您的高德地图 API Key
    key: 'f8b1e8b95e3a514872f912930c9bc21d',
    // 安全密钥（新版本必须配置）
    securityJsCode: '0d5c3b1281576b6f334303936a4ba65d',
    // 使用与安全密钥脚本相同的版本
    version: '2.0',
    plugins: ['AMap.Geocoder', 'AMap.PlaceSearch'],
  };

  // 加载高德地图脚本
  let AMap: any = null;
  let map: any = null;
  let marker: any = null;
  let viewMap: any = null;
  let viewMarker: any = null;
  let geocoder: any = null;

  const { loading, setLoading } = useLoading();
  const visible = ref(false);
  const mapVisible = ref(false);
  const isEdit = ref(false);
  const formRef = ref();
  const stationList = ref<CarStationItem[]>([]);

  // 省市区选项
  const provinceOptions = ref<{ label: string; value: string }[]>([]);
  const cityOptions = ref<{ label: string; value: string }[]>([]);
  const formCityOptions = ref<{ label: string; value: string }[]>([]);
  const districtOptions = ref<{ label: string; value: string }[]>([]);

  // 存储省市区ID映射
  const provinceMap = ref<Map<string, number>>(new Map());
  const cityMap = ref<Map<string, number>>(new Map());

  // 搜索表单
  const searchForm = reactive({
    stationName: '',
    province: '',
    city: '',
    status: undefined as number | undefined,
    partnerId: undefined as number | undefined,
  });

  // 客户相关数据和方法
  const partnerLoading = ref(false);
  const partnerOptions = ref<{ id: number; partnerName: string }[]>([]);

  // 表单数据
  interface FormState {
    id?: number;
    stationName: string;
    province: string;
    city: string;
    district: string;
    address: string;
    stationType: number;
    status: number;
    longitude?: number;
    latitude?: number;
    contactPerson: string;
    contactPhone: string;
    businessHours: string;
    facilities: string;
    remark: string;
    partnerId?: number;
  }

  const formInitialState: FormState = {
    stationName: '',
    province: '',
    city: '',
    district: '',
    address: '',
    stationType: 1,
    status: 1,
    contactPerson: '',
    contactPhone: '',
    businessHours: '',
    facilities: '',
    remark: '',
    partnerId: undefined,
  };

  const form = reactive<FormState>({ ...formInitialState });

  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  const rules = {
    stationName: [{ required: true, message: '请输入站点名称' }],
    province: [{ required: true, message: '请选择所在省份' }],
    city: [{ required: true, message: '请选择所在城市' }],
    address: [{ required: true, message: '请输入详细地址' }],
    stationType: [{ required: true, message: '请选择站点类型' }],
  };

  const renderData = computed(() => {
    console.log('渲染数据:', stationList.value);
    return stationList.value;
  });

  // 获取站点类型文本
  function getStationTypeText(type: number) {
    switch (type) {
      case 1:
        return '普通站点';
      case 2:
        return '超充站';
      case 3:
        return '液冷超充站';
      default:
        return '未知类型';
    }
  }

  // 获取站点类型颜色
  function getStationTypeColor(type: number) {
    switch (type) {
      case 1:
        return 'blue';
      case 2:
        return 'orange';
      case 3:
        return 'purple';
      default:
        return 'gray';
    }
  }

  // 初始化地图
  function initMap() {
    if (!AMap) {
      console.error('高德地图 API 未加载成功');
      Message.error('地图加载失败，请检查网络或刷新页面重试');
      return;
    }

    try {
      // 默认中心点
      const center = [116.397428, 39.90923];

      // 创建地图实例
      map = new AMap.Map('map-container', {
        zoom: 13,
        center,
      });

      // 监听地图错误事件
      map.on('error', (e: any) => {
        console.error('地图加载错误:', e);
        Message.error('地图加载出现错误，请检查控制台');
      });

      // 创建标记
      marker = new AMap.Marker({
        position: center,
        draggable: true,
        cursor: 'move',
      });

      // 将标记添加到地图
      map.add(marker);

      // 初始化地理编码器
      try {
        if (!geocoder) {
          geocoder = new AMap.Geocoder({
            city: '全国', // 城市，默认全国
            radius: 1000, // 范围，默认1000米
          });
        }
      } catch (geocoderError) {
        console.error('地理编码器初始化失败:', geocoderError);
        Message.warning('地理编码器初始化失败，地址搜索功能可能不可用');
      }

      // 监听点击事件
      map.on('click', (e: any) => {
        const lnglat = e.lnglat;
        marker.setPosition(lnglat);
        form.longitude = lnglat.getLng();
        form.latitude = lnglat.getLat();

        // 反向地理编码，获取地址信息
        getAddressByLngLat(lnglat);
      });

      // 监听标记拖拽事件
      marker.on('dragend', (e: any) => {
        const lnglat = marker.getPosition();
        form.longitude = lnglat.getLng();
        form.latitude = lnglat.getLat();

        // 反向地理编码，获取地址信息
        getAddressByLngLat(lnglat);
      });
    } catch (error) {
      console.error('初始化地图失败:', error);
      Message.error('初始化地图失败，请检查网络或刷新页面重试');
    }
  }

  // 根据经纬度获取地址信息
  function getAddressByLngLat(lnglat: any) {
    if (!geocoder) return;

    geocoder.getAddress(lnglat, (status: string, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        const address = result.regeocode;
        if (address) {
          // 如果用户尚未输入地址信息，则自动填充
          const addressComponent = address.addressComponent;

          // 只有当用户未选择省市区时才自动填充
          if (!form.province && addressComponent.province) {
            form.province = addressComponent.province;
            handleFormProvinceChange(form.province);
          }

          if (!form.city && addressComponent.city) {
            // 处理直辖市的情况
            if (
              addressComponent.city.length === 0 &&
              ['北京市', '上海市', '天津市', '重庆市'].includes(form.province)
            ) {
              form.city = form.province;
            } else {
              form.city = addressComponent.city;
            }
            handleFormCityChange(form.city);
          }

          if (!form.district && addressComponent.district) {
            form.district = addressComponent.district;
          }

          // 如果详细地址为空，则自动填充
          if (!form.address) {
            // 使用街道和门牌号作为详细地址
            const street = addressComponent.township || '';
            const streetNumber = addressComponent.streetNumber || '';
            form.address = (street + streetNumber).trim();

            // 如果街道和门牌号都为空，则使用格式化地址
            if (!form.address && address.formattedAddress) {
              // 移除省市区信息，只保留详细地址
              let detailAddress = address.formattedAddress;
              if (form.province) {
                detailAddress = detailAddress.replace(form.province, '');
              }
              if (form.city) {
                detailAddress = detailAddress.replace(form.city, '');
              }
              if (form.district) {
                detailAddress = detailAddress.replace(form.district, '');
              }
              form.address = detailAddress.trim();
            }
          }
        }
      }
    });
  }

  // 根据地址搜索位置
  function searchAddress() {
    if (!AMap) {
      Message.error('地图未加载成功，无法使用地址搜索功能');
      return;
    }

    if (!form.address) {
      Message.warning('请先输入详细地址');
      return;
    }

    // 构建完整地址
    let fullAddress = '';
    if (form.province) {
      fullAddress += form.province;
    }
    if (form.city) {
      fullAddress += form.city;
    }
    if (form.district) {
      fullAddress += form.district;
    }
    fullAddress += form.address;

    console.log('搜索地址:', fullAddress);

    // 显示加载提示
    Message.loading('正在搜索地址...');

    // 构建搜索 URL
    const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
      fullAddress
    )}&city=${encodeURIComponent(form.city || '')}`;

    // 使用 fetch 发送请求
    fetch(searchUrl)
      .then((response) => response.json())
      .then((result) => {
        // 清除加载提示
        Message.clear();

        console.log('地址搜索结果:', result);

        if (
          result.status === '1' &&
          result.geocodes &&
          result.geocodes.length > 0
        ) {
          const location = result.geocodes[0].location.split(',');
          const lng = parseFloat(location[0]);
          const lat = parseFloat(location[1]);

          form.longitude = lng;
          form.latitude = lat;

          // 更新地图位置
          marker.setPosition([lng, lat]);
          map.setCenter([lng, lat]);
          map.setZoom(15);

          Message.success('地址定位成功');
        } else {
          Message.warning('未找到匹配的地址位置');
          // 尝试使用备选方案
          tryAlternativeSearch(fullAddress);
        }
      })
      .catch((error) => {
        console.error('地址搜索失败:', error);
        Message.error('地址搜索失败，请稍后重试');
        // 尝试使用备选方案
        tryAlternativeSearch(fullAddress);
      });
  }

  // 备选方案：使用高德地图 Web 服务 API 搜索地址
  function tryAlternativeSearch(address: string) {
    console.log('尝试使用备选方案搜索地址:', address);

    // 构建搜索 URL
    const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
      address
    )}&city=${encodeURIComponent(form.city || '')}`;

    // 使用 JSONP 方式请求，避免跨域问题
    const script = document.createElement('script');
    const callbackName =
      'amap_geocode_callback_' + Math.random().toString(36).substr(2, 9);

    // 创建全局回调函数
    (window as any)[callbackName] = function (result: any) {
      try {
        console.log('备选方案搜索结果:', result);

        if (
          result.status === '1' &&
          result.geocodes &&
          result.geocodes.length > 0
        ) {
          const location = result.geocodes[0].location.split(',');
          const lng = parseFloat(location[0]);
          const lat = parseFloat(location[1]);

          form.longitude = lng;
          form.latitude = lat;

          // 更新地图位置
          if (marker && map) {
            marker.setPosition([lng, lat]);
            map.setCenter([lng, lat]);
            map.setZoom(15);

            Message.success('地址定位成功（备选方案）');
          } else {
            Message.success('地址定位成功，但地图未加载，已保存经纬度');
          }
        } else {
          console.error('备选方案搜索失败:', result);
          Message.error('备选方案搜索失败: ' + (result.info || '未知错误'));
        }
      } catch (error) {
        console.error('备选方案搜索异常:', error);
      } finally {
        // 清理：移除脚本和回调函数
        document.body.removeChild(script);
        delete (window as any)[callbackName];
      }
    };

    // 设置脚本 URL，添加回调参数
    script.src = searchUrl + '&callback=' + callbackName;
    script.async = true;

    // 处理加载错误
    script.onerror = function (error) {
      console.error('备选方案搜索加载失败:', error);
      Message.error('备选方案搜索加载失败，请检查网络连接');
      document.body.removeChild(script);
      delete (window as any)[callbackName];

      // 最后的备选方案：使用本地坐标拾取器
      Message.info(
        '您可以使用手动输入经纬度的方式，通过高德坐标拾取器获取坐标'
      );
    };

    // 添加脚本到文档
    document.body.appendChild(script);
  }

  // 查看位置
  function viewLocation(record: CarStationItem) {
    if (!record.longitude || !record.latitude) {
      Message.warning('该站点未设置地理位置');
      return;
    }

    mapVisible.value = true;

    // 等待DOM更新后初始化地图
    setTimeout(() => {
      if (!AMap) return;

      // 创建地图实例
      viewMap = new AMap.Map('view-map-container', {
        zoom: 15,
        center: [record.longitude, record.latitude],
      });

      // 创建标记
      viewMarker = new AMap.Marker({
        position: [record.longitude, record.latitude],
        title: record.stationName,
      });

      // 将标记添加到地图
      viewMap.add(viewMarker);

      // 添加信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div>
            <h3>${record.stationName}</h3>
            <p>地址：${record.province}${record.city}${record.district || ''}${
          record.address
        }</p>
            <p>类型：${getStationTypeText(record.stationType)}</p>
            <p>关联客户：${
              record.partnerId ? findPartnerName(record.partnerId) : '未关联'
            }</p>
            <p>联系人：${record.contactPerson || '无'}</p>
            <p>联系电话：${record.contactPhone || '无'}</p>
          </div>
        `,
        offset: new AMap.Pixel(0, -30),
      });

      infoWindow.open(viewMap, viewMarker.getPosition());
    }, 100);
  }

  // 打开坐标拾取器
  function openCoordinatePicker() {
    // 打开高德地图坐标拾取器
    const url = 'https://lbs.amap.com/tools/picker';
    window.open(url, '_blank');

    Message.info('请在坐标拾取器中选择位置，然后复制经纬度到表单中');
  }

  // 手动输入坐标
  function inputCoordinates() {
    const coordsInput = window.prompt(
      '请输入经纬度（格式：经度,纬度）',
      form.longitude && form.latitude
        ? `${form.longitude},${form.latitude}`
        : ''
    );
    if (coordsInput) {
      const coords = coordsInput.split(',');
      if (coords.length === 2) {
        const lng = parseFloat(coords[0].trim());
        const lat = parseFloat(coords[1].trim());

        if (!isNaN(lng) && !isNaN(lat)) {
          form.longitude = lng;
          form.latitude = lat;

          // 更新地图位置
          if (marker && map) {
            marker.setPosition([lng, lat]);
            map.setCenter([lng, lat]);
            map.setZoom(15);
            Message.success('已更新地图位置');
          } else {
            Message.success('已保存经纬度，但地图未加载');
          }
        } else {
          Message.error('无效的经纬度格式');
        }
      } else {
        Message.error('无效的经纬度格式，请使用"经度,纬度"格式');
      }
    }
  }

  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        current: pagination.current,
        size: pagination.pageSize,
        stationName: searchForm.stationName || undefined,
        province: searchForm.province || undefined,
        city: searchForm.city || undefined,
        status: searchForm.status,
        partnerId: searchForm.partnerId,
      };

      console.log('查询参数:', params);

      const res: any = await getCarStationPage(params);
      console.log('获取汽车站点列表响应:', res);

      if (!res) {
        console.error('响应数据为空或格式不正确:', res);
        Message.error('获取汽车站点列表失败: 响应数据格式不正确');
        setLoading(false);
        return;
      }

      if (res.data && res.code === 200 && res.data) {
        // 检查返回的数据结构
        console.log('汽车站点列表原始数据:', res.data);

        // 处理分页数据
        if (res.data.records && Array.isArray(res.data.records)) {
          // 使用处理后的数据
          stationList.value = res.data.records;
          pagination.total = res.data.total || 0;
          pagination.current = res.data.current || 1;
          pagination.pageSize = res.data.size || 10;
          console.log('汽车站点列表数据处理完成:', stationList.value);
        } else {
          console.error('汽车站点列表数据格式不正确:', res.data);
          Message.error('获取汽车站点列表失败: 数据格式不正确');
        }
      } else {
        console.error('获取汽车站点列表失败:', res);
        Message.error(`获取汽车站点列表失败: ${res?.message || '未知错误'}`);
      }
    } catch (err) {
      console.error('获取汽车站点列表异常:', err);
      Message.error(
        '获取汽车站点列表失败: ' +
          (err instanceof Error ? err.message : '未知错误')
      );
    } finally {
      setLoading(false);
    }
  }

  function search() {
    pagination.current = 1;
    fetchData();
  }

  function reset() {
    searchForm.stationName = '';
    searchForm.province = '';
    searchForm.city = '';
    searchForm.status = undefined;
    searchForm.partnerId = undefined;
    pagination.current = 1;
    fetchData();
  }

  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  function openAddDialog() {
    isEdit.value = false;
    Object.assign(form, {
      id: '',
      stationName: '',
      province: '',
      city: '',
      district: '',
      address: '',
      longitude: undefined,
      latitude: undefined,
      contactPerson: '',
      contactPhone: '',
      stationType: 1,
      businessHours: '',
      facilities: '',
      status: 1,
      remark: '',
      partnerId: undefined,
    });

    visible.value = true;

    // 确保省份数据已加载
    if (provinceOptions.value.length === 0) {
      loadProvinceData();
    }

    // 加载客户数据
    if (partnerOptions.value.length === 0) {
      loadPartnerData();
    }

    // 等待DOM更新后初始化地图
    setTimeout(() => {
      initMap();
    }, 100);
  }

  function openEditDialog(record: CarStationItem) {
    console.log('打开编辑对话框，记录:', record);
    isEdit.value = true;
    console.log('设置isEdit为:', isEdit.value);
    Object.assign(form, {
      id: record.id,
      stationName: record.stationName,
      province: record.province,
      city: record.city,
      district: record.district || '',
      address: record.address,
      longitude: record.longitude,
      latitude: record.latitude,
      contactPerson: record.contactPerson || '',
      contactPhone: record.contactPhone || '',
      stationType: record.stationType,
      businessHours: record.businessHours || '',
      facilities: record.facilities || '',
      status: record.status,
      remark: record.remark || '',
      partnerId: record.partnerId || undefined,
    });

    visible.value = true;

    // 确保省份数据已加载
    if (provinceOptions.value.length === 0) {
      loadProvinceData().then(() => {
        // 省份数据加载完成后，处理省市区级联
        handleCascadeData(record);
      });
    } else {
      // 省份数据已加载，直接处理省市区级联
      handleCascadeData(record);
    }

    // 加载客户数据
    if (partnerOptions.value.length === 0) {
      loadPartnerData();
    }

    // 等待DOM更新后初始化地图
    setTimeout(() => {
      initMap();

      // 如果有经纬度，设置标记位置
      if (form.longitude && form.latitude) {
        marker.setPosition([form.longitude, form.latitude]);
        map.setCenter([form.longitude, form.latitude]);
      }
    }, 100);
  }

  // 处理省市区级联数据
  async function handleCascadeData(record: CarStationItem) {
    if (record.province) {
      // 加载城市列表
      try {
        const provinceId = provinceMap.value.get(record.province);
        if (provinceId) {
          const res = (await getCities(provinceId)) as any;
          if (res.code === 200 && res.data) {
            formCityOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 更新城市ID映射
            res.data.forEach((item: Region) => {
              cityMap.value.set(item.name, item.id);
            });

            // 如果有城市，加载区县列表
            if (record.city) {
              const cityId = cityMap.value.get(record.city);
              if (cityId) {
                const districtRes = (await getDistricts(cityId)) as any;
                if (districtRes.code === 200 && districtRes.data) {
                  districtOptions.value = districtRes.data.map(
                    (item: Region) => ({
                      label: item.name,
                      value: item.name,
                    })
                  );
                }
              }
            }
          }
        }
      } catch (error) {
        console.error('加载省市区级联数据失败:', error);
        Message.error('加载省市区级联数据失败');
      }
    }
  }

  // 根据客户ID查找客户名称
  function findPartnerName(partnerId: number): string {
    const partner = partnerOptions.value.find((item) => item.id === partnerId);
    return partner ? partner.partnerName : '未知客户';
  }

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      // 表单验证
      await formRef.value?.validate();

      if (!form.province || !form.city) {
        Message.error('请选择完整的省市信息');
        return false;
      }

      // 构建提交数据
      const submitData = {
        ...form,
        // 确保数值类型正确
        stationType: Number(form.stationType),
        status: Number(form.status),
        partnerId: form.partnerId ? Number(form.partnerId) : undefined,
      };

      console.log('提交数据:', submitData);

      let res: any;
      if (isEdit.value) {
        console.log('调用更新接口');
        res = await updateCarStation(submitData);
      } else {
        console.log('调用新增接口');
        res = await addCarStation(submitData);
      }

      console.log('提交响应:', res);

      if (res.code === 200) {
        Message.success(isEdit.value ? '更新成功' : '新增成功');
        visible.value = false;
        fetchData(); // 刷新列表
        return true;
      } else {
        Message.error(
          `${isEdit.value ? '更新' : '新增'}失败: ${res.message || '未知错误'}`
        );
        return false;
      }
    } catch (err) {
      console.error('表单提交异常:', err);
      Message.error(isEdit.value ? '更新失败' : '新增失败');
      return false;
    }
  };

  // 重置表单
  const resetForm = () => {
    Object.assign(form, formInitialState);
    formRef.value?.resetFields();
  };

  // 删除汽车站点
  async function handleDelete(record: CarStationItem) {
    if (!record.id) {
      Message.error('无效的记录ID');
      return;
    }

    // 确保id是有效的字符串或数字
    const id: string | number = record.id;

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除汽车站点 "${record.stationName}" 吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          const res: any = await deleteCarStation(id);
          console.log('删除汽车站点响应:', res);

          if (!res) {
            console.error('响应数据为空或格式不正确:', res);
            Message.error('删除失败: 响应数据格式不正确');
            return;
          }

          if (res.code === 200) {
            Message.success('删除成功');
            fetchData();
          } else {
            Message.error(`删除失败: ${res.message || '未知错误'}`);
          }
        } catch (err) {
          console.error('删除汽车站点异常:', err);
          Message.error('删除失败');
        }
      },
    });
  }

  // 处理省份变化
  async function handleProvinceChange(value: string) {
    console.log('搜索表单省份变化:', value);
    searchForm.city = '';
    if (value) {
      try {
        const provinceId = provinceMap.value.get(value);
        console.log('获取到省份ID:', provinceId, '省份名称:', value);
        console.log('当前省份映射表:', provinceMap.value);
        if (provinceId) {
          const res = (await getCities(provinceId)) as any;
          console.log('获取城市列表响应:', res);
          if (res.code === 200 && res.data) {
            cityOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 更新城市ID映射
            res.data.forEach((item: Region) => {
              cityMap.value.set(item.name, item.id);
            });
            console.log('城市列表加载成功:', cityOptions.value);
          } else {
            console.error('获取城市列表失败:', res);
            Message.error('获取城市列表失败: ' + (res.message || '未返回数据'));
          }
        } else {
          console.error('未找到省份对应的ID:', value);
          console.log('所有省份选项:', provinceOptions.value);
          Message.error('未找到省份对应的ID');
        }
      } catch (error) {
        console.error('获取城市列表异常:', error);
        Message.error('获取城市列表失败');
        cityOptions.value = [];
      }
    } else {
      cityOptions.value = [];
    }
  }

  // 处理表单省份变化
  async function handleFormProvinceChange(value: string) {
    console.log('表单省份变化:', value);
    form.city = '';
    form.district = '';
    if (value) {
      try {
        const provinceId = provinceMap.value.get(value);
        console.log('获取到省份ID:', provinceId, '省份名称:', value);
        console.log('当前省份映射表:', provinceMap.value);
        if (provinceId) {
          const res = (await getCities(provinceId)) as any;
          console.log('获取城市列表响应:', res);
          if (res.code === 200 && res.data) {
            formCityOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            // 更新城市ID映射
            res.data.forEach((item: Region) => {
              cityMap.value.set(item.name, item.id);
            });
            console.log('表单城市列表加载成功:', formCityOptions.value);
          } else {
            console.error('获取城市列表失败:', res);
            Message.error('获取城市列表失败: ' + (res.message || '未返回数据'));
          }
        } else {
          console.error('未找到省份对应的ID:', value);
          console.log('所有省份选项:', provinceOptions.value);
          Message.error('未找到省份对应的ID');
        }
      } catch (error) {
        console.error('获取城市列表异常:', error);
        Message.error('获取城市列表失败');
        formCityOptions.value = [];
      }
    } else {
      formCityOptions.value = [];
    }
    districtOptions.value = [];
  }

  // 处理表单城市变化
  async function handleFormCityChange(value: string) {
    console.log('表单城市变化:', value);
    form.district = '';
    if (form.province && value) {
      try {
        const cityId = cityMap.value.get(value);
        console.log('获取到城市ID:', cityId, '城市名称:', value);
        console.log('当前城市映射表:', cityMap.value);
        if (cityId) {
          const res = (await getDistricts(cityId)) as any;
          console.log('获取区县列表响应:', res);
          if (res.code === 200 && res.data) {
            districtOptions.value = res.data.map((item: Region) => ({
              label: item.name,
              value: item.name,
            }));
            console.log('区县列表加载成功:', districtOptions.value);
          } else {
            console.error('获取区县列表失败:', res);
            Message.error('获取区县列表失败: ' + (res.message || '未返回数据'));
          }
        } else {
          console.error('未找到城市对应的ID:', value);
          console.log('所有城市选项:', formCityOptions.value);
          Message.error('未找到城市对应的ID');
        }
      } catch (error) {
        console.error('获取区县列表异常:', error);
        Message.error('获取区县列表失败');
        districtOptions.value = [];
      }
    } else {
      districtOptions.value = [];
    }
  }

  // 加载省份数据
  async function loadProvinceData() {
    try {
      const res = (await getProvinces()) as any;
      console.log('获取省份列表响应:', res);
      if (res.code === 200 && res.data) {
        provinceOptions.value = res.data.map((item: Region) => ({
          label: item.name,
          value: item.name,
        }));
        // 存储省份ID映射
        res.data.forEach((item: Region) => {
          provinceMap.value.set(item.name, item.id);
        });
        console.log('省份数据加载成功:', provinceOptions.value);
        console.log('省份ID映射:', provinceMap.value);
      } else {
        console.error('获取省份列表失败:', res);
        Message.error('获取省份列表失败: ' + (res.message || '未返回数据'));
      }
    } catch (error) {
      console.error('获取省份列表异常:', error);
      Message.error('获取省份列表失败');
    }
  }

  // 获取客户列表
  async function loadPartnerData() {
    partnerLoading.value = true;
    try {
      // 使用新的不分页接口获取所有客户
      const res = await getAllPartners({ status: 1 }); // 只获取启用状态的客户
      // 注意：request.ts 中的拦截器已经处理了响应，直接使用返回值
      if (res && Array.isArray(res.data)) {
        partnerOptions.value = res.data.map((item: any) => ({
          id: item.id,
          partnerName: item.partnerName,
        }));
        console.log('客户数据加载成功:', partnerOptions.value);
      } else {
        console.error('获取客户列表失败:', res);
        Message.error('获取客户列表失败: 未返回有效数据');
      }
    } catch (error) {
      console.error('获取客户列表异常:', error);
      Message.error('获取客户列表失败');
    } finally {
      partnerLoading.value = false;
    }
  }

  // 搜索客户
  async function searchPartners(keyword: string) {
    if (!keyword) return;
    partnerLoading.value = true;
    try {
      // 仍然使用分页接口进行搜索，但是结果更精确
      const res = await getPartnerList({
        size: 20,
        current: 1,
        partnerName: keyword,
        status: 1, // 只搜索启用状态的客户
      });
      // 注意：request.ts 中的拦截器已经处理了响应，直接使用返回值
      if (res && res.data && res.data.records) {
        partnerOptions.value = res.data.records.map((item: any) => ({
          id: item.id,
          partnerName: item.partnerName,
        }));
      }
    } catch (error) {
      console.error('搜索客户异常:', error);
    } finally {
      partnerLoading.value = false;
    }
  }

  // 防抖处理的地址搜索
  const debounceSearchAddress = debounce((value: string) => {
    if (value && form.province && form.city) {
      // 构建完整地址
      let fullAddress = '';
      if (form.province) {
        fullAddress += form.province;
      }
      if (form.city) {
        fullAddress += form.city;
      }
      if (form.district) {
        fullAddress += form.district;
      }
      fullAddress += value;

      // 构建搜索 URL
      const searchUrl = `https://restapi.amap.com/v3/geocode/geo?key=23c24009c5a2548156cea739bef3ab7c&address=${encodeURIComponent(
        fullAddress
      )}&city=${encodeURIComponent(form.city || '')}`;

      // 使用 fetch 发送请求
      fetch(searchUrl)
        .then((response) => response.json())
        .then((result) => {
          console.log('地址搜索结果:', result);

          if (
            result.status === '1' &&
            result.geocodes &&
            result.geocodes.length > 0
          ) {
            const location = result.geocodes[0].location.split(',');
            const lng = parseFloat(location[0]);
            const lat = parseFloat(location[1]);

            form.longitude = lng;
            form.latitude = lat;

            // 更新地图位置
            if (marker && map) {
              marker.setPosition([lng, lat]);
              map.setCenter([lng, lat]);
              map.setZoom(15);
            }
          }
        })
        .catch((error) => {
          console.error('地址搜索失败:', error);
        });
    }
  }, 1000);

  onMounted(async () => {
    // 加载省份数据
    await loadProvinceData();

    // 设置安全密钥配置（必须在加载地图脚本之前设置）
    window._AMapSecurityConfig = {
      securityJsCode: AMAP_CONFIG.securityJsCode,
      serviceHost: `https://restapi.amap.com`,
    };

    // 加载高德地图
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=${AMAP_CONFIG.version}&key=${
      AMAP_CONFIG.key
    }&plugin=${AMAP_CONFIG.plugins.join(',')}`;

    script.onerror = (error) => {
      console.error('高德地图 API 加载失败:', error);
      Message.error('高德地图加载失败，将使用手动输入经纬度的方式');
    };

    script.onload = () => {
      if (window.AMap) {
        AMap = window.AMap;
        console.log('高德地图 API 加载成功');
        // 地图加载成功后初始化地图
        initMap();
      } else {
        console.error('高德地图 API 加载失败: AMap 对象不存在');
      }
    };

    document.head.appendChild(script);

    // 获取汽车站点列表
    fetchData();

    // 加载客户数据
    loadPartnerData();
  });

  onBeforeUnmount(() => {
    // 销毁地图实例
    if (map) {
      map.destroy();
      map = null;
    }
    if (viewMap) {
      viewMap.destroy();
      viewMap = null;
    }
  });

  // 查看设备
  function viewDevices(record: CarStationItem) {
    // 跳转到设备页面，并传递站点ID和站点名称
    router.push({
      path: '/station/device',
      query: {
        stationId: record.id,
        stationName: record.stationName,
      },
    });
  }

  // 查看站点订单
  function viewStationOrders(record: CarStationItem) {
    router.push({
      path: '/charging/order',
      query: {
        stationId: record.id,
        stationName: record.stationName,
      },
    });
  }
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  // 表格响应式处理
  :deep(.arco-table) {
    @media (max-width: 1200px) {
      .arco-table-th,
      .arco-table-td {
        padding: 12px 8px;
      }
    }

    @media (max-width: 768px) {
      .arco-table-th,
      .arco-table-td {
        padding: 10px 6px;
        font-size: 13px;
      }
    }
  }

  .action-btns {
    display: flex;
    button {
      margin-right: 8px;
    }
  }

  .search-form {
    margin-bottom: 16px;

    .form-row {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 16px;

      .form-col {
        margin-right: 24px;
        margin-bottom: 12px;
      }

      .form-col-flex {
        flex: 1;
        min-width: 280px;
      }
    }

    .right-btns {
      display: flex;
      justify-content: flex-end;

      button {
        margin-left: 8px;
      }
    }
  }

  .station-modal {
    :deep(.arco-modal-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;

      .arco-modal-title {
        font-size: 18px;
        font-weight: 500;
      }
    }

    :deep(.arco-modal-body) {
      padding: 20px;
      max-height: 80vh;
      overflow-y: auto;
    }
  }

  .station-form {
    .form-card {
      margin-bottom: 20px;
      border-radius: 4px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

      :deep(.arco-card-header) {
        border-bottom: 1px solid var(--color-border-2);
        padding: 12px 16px;

        .arco-card-header-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--color-text-1);
        }
      }

      :deep(.arco-card-body) {
        padding: 16px;
      }
    }

    :deep(.arco-form-item-label-col) {
      font-weight: 500;
    }

    :deep(.arco-radio-group-button) {
      .arco-radio {
        padding: 0 16px;
      }
    }

    .form-row {
      display: flex;
      flex-wrap: wrap;

      .form-col {
        width: 48%;
        margin-right: 2%;
        margin-bottom: 16px;

        &.full-width {
          width: 98%;
        }
      }
    }

    // 地理位置卡片中的所有表单项标签向左靠齐
    .location-card {
      :deep(.arco-form) {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;

        .arco-form-item {
          margin-bottom: 16px;

          &:nth-last-child(-n + 2) {
            grid-column: 1 / -1;
          }

          .arco-form-item-label-col {
            text-align: left;
            padding-left: 0;
            width: 80px;
            flex: 0 0 80px;
          }

          .arco-form-item-wrapper-col {
            flex: 1;
            width: calc(100% - 80px);
          }
        }
      }
    }

    // 详细地址输入框样式
    .address-item {
      :deep(.arco-form-item-label-col) {
        text-align: left;
        padding-left: 0;
        width: 80px;
        flex: 0 0 80px;
      }

      :deep(.arco-form-item-wrapper-col) {
        flex: 1;
        width: calc(100% - 80px);
      }

      :deep(.arco-input) {
        width: 100%;
      }
    }

    // 全宽表单项样式（站点设施和备注）
    .full-width-item {
      :deep(.arco-form-item-label-col) {
        text-align: left;
        padding-left: 0;
        width: 80px;
        flex: 0 0 80px;
      }

      :deep(.arco-form-item-wrapper-col) {
        flex: 1;
        width: calc(100% - 80px);
      }

      :deep(.arco-textarea) {
        width: 100%;
      }
    }

    .map-container {
      width: 100%;
      height: 300px;
      margin-bottom: 16px;
      border: 1px solid var(--color-border);
      border-radius: 4px;
      position: relative;
      overflow: hidden;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

      .map-info {
        position: absolute;
        bottom: 0;
        right: 0;
        background: rgba(255, 255, 255, 0.8);
        padding: 8px 12px;
        border-top-left-radius: 4px;
        font-size: 12px;

        p {
          margin: 4px 0;
        }

        .map-tip {
          color: var(--color-text-3);
          font-style: italic;
        }
      }
    }

    .form-footer {
      display: flex;
      justify-content: center;
      margin-top: 24px;
      padding: 16px 0;

      .arco-space {
        .arco-btn {
          min-width: 80px;
        }
      }
    }
  }

  .view-map-container {
    width: 100%;
    height: 400px;
  }

  .status-tag {
    &.status-1 {
      color: #165dff;
      background-color: #e8f3ff;
    }

    &.status-0 {
      color: #86909c;
      background-color: #f2f3f5;
    }
  }

  .station-type-tag {
    &.type-1 {
      color: #165dff;
      background-color: #e8f3ff;
    }

    &.type-2 {
      color: #ff7d00;
      background-color: #fff3e8;
    }

    &.type-3 {
      color: #722ed1;
      background-color: #f5e8ff;
    }
  }

  .manual-location-input {
    margin-top: 16px;
    padding: 16px;
    border: 1px solid var(--color-border);
    border-radius: 4px;
    background-color: var(--color-fill-2);

    ol {
      margin-top: 8px;
      padding-left: 20px;
    }

    a {
      color: var(--color-primary);
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .text-muted {
    color: var(--color-text-3);
    font-style: italic;
  }

  .operations-wrapper {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .action-group {
      display: flex;
      gap: 8px;
      justify-content: flex-end;
      align-items: center;
      flex-wrap: wrap;

      .arco-btn {
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
        transition: all 0.2s;
        min-width: 72px;
        font-weight: 400;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
        }

        &[status] {
          &:hover {
            opacity: 0.85;
          }
        }
      }
    }
  }

  // 全局按钮样式优化
  :deep(.arco-btn) {
    border-radius: 5px;

    &.arco-btn-shape-round {
      border-radius: 20px;
    }
  }
</style>
